﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ParserCore;
using NDimArrayNamespace;
using Memory_Access;

namespace Engine
{
    public class EngineManager
    {
        private EngineVisitor engineVisitor;

        public FunctionTable currentFolderTable;
        public FunctionTable pathTable;


        private EngineManager()
        {
            engineVisitor = new EngineVisitor();
            // Da li se builtin funkcije i funkcije standardne biblioteke nalaze u Pathu? Ako ne, pri instanciranju EngineManagera potrebno je dodati i te funkcije u PathTable.
        }
        static private EngineManager _instance = null;
        
        static public EngineManager Instance
        {
            get
            {
                if (_instance == null)
                    _instance = new EngineManager();
                return _instance;
            }
        }
 
        public void Execute(string command, Dictionary<string, string> currentFolderFunctions, List<Dictionary<string, string>> PathFunctions)
        {
            // pri svakom izvrsavanju naredbe Path i CurrentFolder funkcije se ucitavaju u svoje tabele jer se one mogu menjati u toku korsicenja programa
           
            for (int i=0; i<PathFunctions.Count; i++)
                pathTable.AddFunctions(PathFunctions[i]);
            currentFolderTable.AddFunctions(currentFolderFunctions);

            Statement commandStatement = null;
            ParsingEngine commandParser = new ParsingEngine();
            try
            {
                commandStatement = commandParser.Parse(command);
            }
            catch (ParserException exception)
            {
                OnConsoleEvent("Parser error: " + exception.ParserErrorMessage);
                return;
            }
            commandStatement.Accept(engineVisitor);
        }

        public delegate void ConsoleEventHandler(string text);
        public event ConsoleEventHandler ConsoleEvent = null;
        public void OnConsoleEvent(string text)
        {
            if(this.ConsoleEvent!= null)
                this.ConsoleEvent(text);
        }
    }
}
